package com.cxyzy.toptabdemo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.PagerAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.BaseOnTabSelectedListener
import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViewPager()
        initTabLayout()
    }

    private fun initViewPager() {
        addViews()
        viewPager.addOnPageChangeListener(TabLayoutOnPageChangeListener(tabLayout))
        setAdapter()
    }

    private fun addViews() {
        val view1 = LayoutInflater.from(this).inflate(R.layout.view_pager_1, null)
        val view2 = LayoutInflater.from(this).inflate(R.layout.view_pager_2, null)

        viewPager.addView(view1)
        viewPager.addView(view2)
    }

    private fun setAdapter() {
        viewPager.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return viewPager.childCount
            }

            override fun isViewFromObject(view: View, obj: Any): Boolean {
                return view === obj
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                return viewPager.getChildAt(position)
            }
        }
    }

    private fun initTabLayout() {
        tabLayout.addOnTabSelectedListener(object : BaseOnTabSelectedListener<TabLayout.Tab> {

            override fun onTabSelected(tab: TabLayout.Tab?) {
                val position = tab!!.position
                viewPager.currentItem = position
            }

            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }
        })
    }
}
